<script setup>
//导入库
import {Web3} from 'web3'
import {ref} from 'vue'
import {ABI,contractAddress} from './contracts/PetrolTx'

//构建实例
const web3 = new Web3(window.ethereum)
const contract = new web3.eth.Contract(ABI,contractAddress)

//当前地址
const currentAddress = ref(0)
//当前余额
const balance = ref(0)
//连接状态
const connected = ref(false)
//石油库存
const totalBalance = ref(0)
//购买量
const amount = ref(0)

//连接钱包
const connectMetamask = ()=>{
  //先检查浏览器是否有钱包插件
  if(window.ethereum){
    window.ethereum.request({ method: 'eth_requestAccounts' })
    .then(()=>{
      console.log("连接成功!")
      connected.value = true
      //获取当前链接账户的地址
      web3.eth.getAccounts()
      .then((accounts)=>{
          currentAddress.value = accounts[0]
          console.log("当前账户地址："+currentAddress.value)
      })
    })
  }
}
//查询账户余额
const checkBalance = async()=>{
  await web3.eth.getBalance(currentAddress.value).then((res)=>{
    balance.value = res
  })
}
//查询石油总量
const checkTotal = async()=>{
  await contract.methods.checkBalance().call()
  .then((inventory)=>{
    // console.log(inventory)
    totalBalance.value = inventory
  })
}

//模拟购入
const purchasePetrol = async()=>{
  console.log(amount.value * 1000)
  contract.methods.buyPetrol(amount.value).send({from:currentAddress.value})
  .catch((error)=>{
        alert("交易失败")
    })
}

</script>

<template>
  <h1>vue3调用智能合约测试</h1>
  <div>
    <van-button type="primary" @click="connectMetamask" v-if="!connected">连接钱包</van-button><br>
    <van-button type="success" @click="checkTotal" v-if="connected">石油总量</van-button><br>
    <van-button type="warning" @click="checkBalance" v-if="connected">账户余额</van-button><br>
    <van-button type="danger" @click="purchasePetrol(amount)" v-if="connected">购入石油</van-button>
    <van-field
      v-if="connected"
      v-model="amount"
      placeholder="请输入购入量"
      :rules="[{ required: true, message: '请填写购入量' }]"
    /><br>
    <van-cell-group v-if="connected">
    <van-cell title="当前地址：">{{currentAddress}}</van-cell>
    <van-cell title="账户余额：">{{balance}}</van-cell>
    <van-cell title="石油存量：">{{totalBalance}}</van-cell>
    </van-cell-group>
  </div>
</template>

<style scoped>
</style>
